package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.Header
import org.apache.http.HttpEntity
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClientBuilder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: api7MoorRecord*
 */

public class apiFileProxy implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiFileProxy.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String result = "";

        String fileurl = KHUtil.FastJsonNull(request.getParameter("fileurl"));
        String type = KHUtil.FastJsonNull(request.getParameter("type"));
        log.debug("原始Get请求参数fileurl:" + fileurl + " type:" + type);

        if (fileurl == null || "".equals(fileurl.trim())) {
            return; // url为空时不处理
        }

        try {
            // 获取token

            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse fileresponse = null;
            log.debug("要转发的文件地址：" + fileurl);
            try {
                fileresponse = httpClient.execute(new HttpGet(fileurl));
                HttpEntity entity = fileresponse.getEntity();
                int status = fileresponse.getStatusLine().getStatusCode();
                response.setStatus(status);
                if (status == 200 && entity != null) {

                    Header[] headers = fileresponse.getAllHeaders();
                    log.debug("Header[] : " + headers.toString());
                    for (Header header : headers) {
                        log.debug("Key : " + header.getName() + " ,Value : " + header.getValue());
                    }

                    //Content-Type根据文件实际类型设置
                    response.setHeader("Content-Type", "application/mp3;charset=utf-8");
                    response.setHeader("Content-Length", entity.getContentLength() + "");
                    response.setHeader("Content-Encoding", "UTF-8");
                    response.setHeader("Content-Disposition", "attachment;fileName=ceshi.mp3");

                    InputStream is = entity.getContent();
                    OutputStream os = response.getOutputStream();

                    byte[] buffer = new byte[1024];
                    int ch;
                    while ((ch = is.read(buffer)) != -1) {
                        os.write(buffer, 0, ch);
                    }
                    is.close();
                    os.flush();
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        fileresponse.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        } catch (Exception e) {
            log.error("接口处理异常", e);

        }

        return;
    }

}
